package com.yl.chainStore.control

import cn.hutool.core.collection.CollUtil
import cn.hutool.core.io.IoUtil
import cn.hutool.core.util.IdUtil
import cn.hutool.poi.excel.ExcelUtil
import cn.hutool.poi.excel.WorkbookUtil
import cn.hutool.poi.excel.WorkbookUtil.*
import org.apache.poi.ss.util.SheetUtil
import org.apache.xmlbeans.impl.common.IOUtil
import org.slf4j.LoggerFactory
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import javax.servlet.ServletOutputStream
import javax.servlet.http.HttpServletResponse

/**
 *
 * create by 2021/5/11.
 * @author udbjqr
 */
open class BaseCtrl {
    protected val log = LoggerFactory.getLogger(this::class.java)!!


    protected open fun export(response:HttpServletResponse , list: Collection<*>?, headAlias: MutableMap<String?, String?>) {
        try {
//            val df = SimpleDateFormat("yyyy-MM").format(Date())
//            val dir = File(resources + df)
//            if (!dir.exists()) {
//                dir.mkdirs()
//            }
//            val filename: String = IdUtil.getSnowflake().nextId().toString() + ".xlsx"
            // 这里放文件路径
//            val filePath: String = resources + df + File.separator + filename
//            log.info("拿到文件路径为====={}",filePath)
            val writer = ExcelUtil.getWriter()
            if (CollUtil.isEmpty(list)) {
                // 下载模板：只写标题行
                writer.writeHeadRow(headAlias.values)
            } else {
                // 导出数据：写入标题行和数据行
                writer.setHeaderAlias(headAlias)
                // 只导出Alias列
                writer.setOnlyAlias(true)
                writer.write(list, true)
            }
            //自适应宽度
            val columnCount: Int = writer.getColumnCount()
            for (i in 0 until columnCount) {
                var width = SheetUtil.getColumnWidth(writer.getSheet(), i, false)
                if (width != -1.0) {
                    if (width > 100) {
                        width = 100.0
                        writer.setColumnWidth(i, Math.toIntExact(Math.round(width)))
                    } else {
                        width *= 256.0
                        //此处可以适当调整，调整列空白处宽度
                        width += 4000.0
                        writer.setColumnWidth(i, Math.toIntExact(Math.round(width / 256)))
                    }
                }
            }
        response.setContentType("application/vnd.ms-excel;charset=utf-8")
        val outputStream = response.outputStream

        writer.flush(outputStream,true)
        writer.close()
        IoUtil.close(outputStream)
        // 前端修改了下载方法，需要返回输出流
//            val wb: Workbook = WorkbookUtil.createBook(filePath)
//            wb.write(ServletUtils.getResponse().getOutputStream())
////            wb.close()
            // 导出后删除文件
//            FileUtil.del(filePath)
        } catch (e: Exception) {
            throw java.lang.Exception(e.message)
        }
    }



}
